<template>
  <div class="tableBasic">
    <div class="search">
      <div class="sl">
        <el-input v-model="info.form.name" placeholder="请输入姓名" />
        <el-date-picker
          v-model="search.date"
          type="datetimerange"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
        <el-select v-model="info.form.status" placeholder="请选择状态">
          <el-option label="正常" :value="1" />
          <el-option label="关闭" :value="0" />
        </el-select>

        <el-button plain @click="searchTableData({page: 1})">搜索</el-button>
      </div>
      <div class="sr">
        <el-button type="success" plain @click="openInfo()">新增</el-button>
      </div>
    </div>

    <el-table ref="tableRef" :data="tableData" border stripe v-loading="loading">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="ID" show-overflow-tooltip />
      <el-table-column prop="date" label="日期" />
      <el-table-column prop="name" label="名字" />
      <el-table-column prop="address" label="地址" show-overflow-tooltip />
      <el-table-column prop="zip" label="邮编" />
      <el-table-column prop="status" label="状态" :formatter="(row) => row.status ? '正常' : '关闭'" />
      <el-table-column prop="operation" label="操作" width="180" align="center">
        <template #default="{row, $index}">
          <el-button type="warning" plain @click="openInfo(row)">修改</el-button>
          <el-button type="danger" plain @click="delInfo($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <div class="pl">
        <span>批量操作：</span>
        <el-button type="danger" plain @click="batchDelete">删除</el-button>
      </div>
      <el-pagination
        :loading="loading"
        background
        layout="prev, pager, next"
        :current-page="search.page"
        :page-size="search.pageSize"
        @current-change="(page) => searchTableData({page})"
        :total="1000"
      />
    </div>

    <el-dialog v-model="info.show" title="新增/修改信息" @close="closeInfo">
      <el-form ref="formRef" :model="info.form" :rules="info.rules" label-width="100" style="padding-right: 50px">
        <el-form-item label="ID：">
          <el-input v-model="info.form.id" disabled />
        </el-form-item>
        <el-form-item label="日期：">
          <el-input v-model="info.form.date" disabled />
        </el-form-item>
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="info.form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input v-model="info.form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-select v-model="info.form.status" placeholder="请选择状态">
            <el-option label="正常" :value="1" />
            <el-option label="关闭" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮编：" prop="zip">
          <el-input v-model="info.form.zip" placeholder="请输入邮编" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeInfo">取消</el-button>
          <el-button type="primary" @click="editInfo">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { onMounted, reactive, ref, toRefs, getCurrentInstance } from 'vue'
import { uuid } from '@/utils/index.js'
export default {
  setup() {

    const { proxy } = getCurrentInstance()

    const tableRef = ref(null)
    const formRef = ref(null)

    const data = reactive({
      loading: false,
      search: {
        date: '',
        page: 1,
        pageSize: 10
      },
      tableData: [],
      info: {
        show: false,
        type: '',
        form: {},
        rules: {
          name: { required: true, message: '请输入姓名', trigger: 'blur' },
          address: { required: true, message: '请输入地址', trigger: 'blur' },
          status: { required: true, message: '请选择状态', trigger: 'blur' },
          zip: { required: true, message: '请输入邮编', trigger: 'blur' },
        }
      }
    })

    onMounted(async () => {
      data.loading = true
      const { data: value } = await api.getTableData()
      data.loading = false
      data.tableData = value
    })

    const methods = {
      async searchTableData(params) {
        data.search = { ...data.search, ...params }
        data.loading = true
        const { data: value } = await api.getTableData()
        data.loading = false
        data.tableData = value
      },
      openInfo(row) {
        data.info.show = true
        data.info.type = row ? 'add' : 'edit'
        data.info.form = row || {
          id: uuid(),
          date: dayjs().format('YYYY-MM-DD HH:mm'),
        }
      },
      closeInfo() {
        data.info.show = false
        data.info.form = {}
      },
      editInfo() {
        formRef.value.validate((valid, fields) => {
          if (!valid) return proxy.$message.error(Object.values(fields)[0][0].message)
          const editIndex = data.tableData.findIndex(v => v.id == data.info.form.id)
          if (~editIndex) {
            data.tableData[editIndex] = data.info.form
          } else {
            data.tableData.push(data.info.form)
          }
          methods.closeInfo()
        })
      },
      delInfo(index) {
        proxy.$messageBox.confirm(
          '你正在进行删除操作，是否继续?',
          '温馨提示',
          {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          data.tableData.splice(index, 1)
          proxy.$message.success('删除成功')
        })
      },
      batchDelete() {
        const selection = tableRef.value.getSelectionRows()
        if (!selection.length) return proxy.$message.error("请至少选中一项以进行操作")
        proxy.$messageBox.confirm(
          '你正在进行删除操作，是否继续?',
          '温馨提示',
          {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          data.tableData = data.tableData.filter(v => !~selection.findIndex(item => item.id == v.id))
          proxy.$message.success('删除成功')
        })
      },
    }

    const api = {
      getTableData() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            const arr = []
            for (let i = 0; i < 10; i++) {
              arr.push({
                id: uuid(),
                date: dayjs().format('YYYY-MM-DD HH:mm'),
                name: "迪丽热巴",
                address: "**省**市**区******街道***路**号",
                status: 1,
                zip: "CA 90036"
              })
            }
            resolve({
              code: 200,
              data: arr,
              msg: '请求成功',
            })
          }, 1000)
        })
      }
    }

    return {
      tableRef,
      formRef,
      ...toRefs(data),
      ...methods,
    }
  }
}

</script>